import router, { asyncRouter } from './router'
import store from '@/store'
import getPageTitle from '@/utils/get-page-title'
// no redirect whitelist
const whiteList = ['/login', '/404']
// 多个路由守卫,按顺序执行
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = getPageTitle(to.meta.title)
  next()
})
router.beforeEach(async(to, from, next) => {
  // 取出token
  const token = store.state.user.token
  console.log('路由守卫.....', to, from)
  if (token) {
    if (to.path === '/login') {
      console.log('已经登录没办法访问login了')
      next('/')
    } else {
      // 不去登录页
      if (!store.getters.userId) {
        const menus = await store.dispatch('user/getUserInfo')
        console.log('当前用户可以访问的页面是', menus)
        console.log('当前系统中用户能够访问的所有的页面', asyncRouter)
        const filterRoutes = asyncRouter.filter(route => {
          return menus.includes(route.children[0].name)
        })
        // { path: '*', redirect: '/404', hidden: true }
        filterRoutes.push({ path: '*', redirect: '/404', hidden: true })
        router.addRoutes(filterRoutes) // 动态添加
        // 根据用户实际能访问几个页面来决定从整体8个页面路由设置中过滤出来几个然后保存到Vuex中
        store.commit('menu/setMenuList', filterRoutes)
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
      } else {
        next()
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      console.log('你没有登录,转到登录页')
      next('/login')
    }
  }
  // next()
})
